<template>
  <el-dialog v-model="dialogVisible" title="设置权限" width="500">
    <el-form
      ref="formRef"
      v-loading="loading"
      style="max-width: 600px"
      :model="formData"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="访问权限" prop="accessMode">
        <el-segmented v-model="formData.accessMode" :options="locationOptions" />
      </el-form-item>
      <el-form-item
        v-if="accessModeConfig.isShow"
        :label="accessModeConfig.label"
        prop="accessMode"
      >
        <user-list v-model="formData.accessList" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button :disabled="loading" @click="handleClose">取消</el-button>
        <el-button type="primary" :disabled="loading" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import UserList from "@/components/UserList/index.vue"
import ProviderAPI from "@/api/virtual-number/provider.api"
import useToggle from "@/hooks/useToggle"
const [loading, setLoading] = useToggle()
const [dialogVisible, setDialogVisible] = useToggle()

const emits = defineEmits(["refresh"])

const formData = ref({
  accessList: [],
  accessMode: "public",
  id: null,
  providerName: null,
})

const rules = reactive({
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
})

const enumAccessModes = {
  public: "公开",
  whitelist: "白名单",
  blacklist: "黑名单",
}

const locationOptions = computed(() => {
  return Object.keys(enumAccessModes).map((key) => ({
    label: enumAccessModes[key],
    value: key,
  }))
})

const accessModeConfig = computed(() => {
  const isShow = ["whitelist", "blacklist"].includes(formData.value.accessMode)
  const label = enumAccessModes[formData.value.accessMode]
  return { label, isShow }
})

const formRef = ref(null)
const init = (row) => {
  setDialogVisible(true)
  formData.value = {
    accessList: [],
    accessMode: "",
    id: null,
    providerName: null,
  }
  nextTick(() => {
    formRef.value.resetFields()

    if (row) {
      formData.value = JSON.parse(JSON.stringify(row))
    }
  })
}

const submit = async () => {
  await formRef.value.validate((valid) => {
    if (!valid) return
    setLoading(true)
    if (formData.value.id) {
      return ProviderAPI.update(
        {
          accessList: formData.value.accessMode != "public" ? formData.value.accessList : [],
          accessMode: formData.value.accessMode,
        },
        formData.value.providerName
      )
        .then(() => {
          emits("refresh")
        })
        .finally(() => {
          handleClose()
          setLoading(false)
        })
    }
  })
}

const handleClose = () => {
  setDialogVisible(false)
}

defineExpose({
  init,
})
</script>
